package com.ze.threadpool.config;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class CustomNameThreadFactory implements ThreadFactory {
    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup threadGroup;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    public CustomNameThreadFactory(String threadName) {
        SecurityManager securityManager = System.getSecurityManager();
        threadGroup =
                (securityManager != null)
                        ? securityManager.getThreadGroup()
                        : Thread.currentThread().getThreadGroup();
        // 如果没有设置线程名称，赋予初始值
        if (threadName == null || "".equals(threadName.trim())) {
            threadName = "pool";
        }
        // 为每一个线程取一个不冲突的名字
        namePrefix = threadName
                + "-" + poolNumber.getAndIncrement()
                + "-thread-";
    }

    @Override
    public Thread newThread(Runnable r) {
        // 创建相应的Thread任务
        Thread thread = new Thread(threadGroup, r, namePrefix + threadNumber.getAndIncrement());
        // 检查是否为守护线程
        if (thread.isDaemon()) {
            // 如果是守护线程，则设置为非守护线程
            thread.setDaemon(false);
        }
        // 判断线程的优先级是否为默认优先级5
        if (thread.getPriority() != Thread.NORM_PRIORITY) {
            // 如果不是，则将该线程设置为默认优先级
            thread.setPriority(Thread.NORM_PRIORITY);
        }
        return thread;
    }
}